package com.dx.core.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 加载自定义通用配置
 *
 * @author xufeng
 * @since 18.04.2023
 */
public class CustomPropertiesValidate implements EnvironmentPostProcessor {
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    /**
     * 配置目录
     */
    private static final String CONFIG_HOME = "config/datart.conf";


    /**
     * 线上配置
     */
    private static final String DEFAULT_APPLICATION_CONFIG = "config/profiles/application-config.yml";
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {


    }

    /**
     * 加载自定义的配置文件
     * @return
     */
    private Properties loadCustomProperties() {
        Properties properties = new Properties();
        File file = new File(concatPath(System.getProperty("user.dir"), CONFIG_HOME));
        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            properties.load(inputStream);
        } catch (Exception e) {
            System.err.println("Failed to load the datart configuration (config/datart.conf), use application-config.yml");
            return new Properties();
        }
        List<Object> removeKeys = new ArrayList<>();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String val = String.valueOf(entry.getValue()).trim();
            if (StringUtils.isBlank(val)) {
                removeKeys.add(entry.getKey());
            }
            entry.setValue(val);
        }
        for (Object key : removeKeys) {
            properties.remove(key);
        }
        return properties;
    }



    public static String concatPath(String... paths) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < paths.length; i++) {
            String path = paths[i];
            if (StringUtils.isBlank(path)) {
                continue;
            }
            path = StringUtils.appendIfMissing(path, "/");
            if (i != 0) {
                path = StringUtils.removeStart(path, "/");
            }
            if (i == paths.length - 1) {
                path = StringUtils.removeEnd(path, "/");
            }
            stringBuilder.append(path);
        }
        return StringUtils.removeEnd(stringBuilder.toString(), "/");
    }
}
